package com.itheima.dubbo.api;

import com.itheima.domain.mongo.RecommendUser;
import com.itheima.domain.vo.PageResult;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author 阿鹏
 * @date 2021/1/26 20:10
 */
@Service
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public PageResult<RecommendUser> recommendUserList(Long userId, int page, int pagesize) {
        // 分页查询
        Query query = Query.query(Criteria.where("toUserId").is(userId))
                .with(Sort.by(Sort.Order.desc("score"))) // 用过缘分值倒序排序
                .with(PageRequest.of(page-1,pagesize));
        List<RecommendUser> userList = mongoTemplate.find(query, RecommendUser.class);
        // 总数量
        int counts = (int) mongoTemplate.count(query, RecommendUser.class);
        // 总页数
        int pages = (int) Math.ceil(counts * 1.0 / pagesize);
        return new PageResult<RecommendUser>(counts,pagesize,1,page,userList);
    }

    @Override
    public Long findRecommendUserScore(long userId, long toUserId) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("toUserId").is(toUserId));
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        if (recommendUser == null) {
            return 95L;
        }
        return recommendUser.getScore().longValue();
    }

    @Override
    public RecommendUser findMaxScoreRecommendUser(Long userId) {
        Query query = Query.query(Criteria.where("toUserId").is(userId))
                .with(Sort.by(Sort.Order.desc("score"))) // 根据缘分值排序
                .limit(1); // 取第一个
        return mongoTemplate.findOne(query, RecommendUser.class);
    }
}
